package springDemo.util;

import java.io.File;
import java.io.Serializable;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static SessionFactory sessionFactory = null;
	static {
		Configuration configuration = new Configuration().configure(new File("./src/springDemo/hibernate.cfg.xml"));
		sessionFactory = configuration.buildSessionFactory();
	}

	public static Session getSession() {
		return sessionFactory.openSession();
	}

	public static void save(Object entity) {
		Session session = null;
		Transaction tansaction = null;
		try {
			session = HibernateUtil.getSession();
			tansaction = session.beginTransaction();
			session.saveOrUpdate(entity);
			tansaction.commit();
		} catch (HibernateException e) {
			throw e;
		} finally {
			if (session != null)
				session.close();
		}
	}

	public static void delete(Object entity) {
		Session session = null;
		Transaction tansaction = null;
		try {
			session = HibernateUtil.getSession();
			tansaction = session.beginTransaction();
			session.delete(entity);
			tansaction.commit();
		} catch (HibernateException e) {
			throw e;
		} finally {
			if (session != null)
				session.close();
		}

	}

	public static void update(Object entity) {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			session.update(entity);
			tx.commit();
		} catch (HibernateException e) {
			throw e;
		} finally {
			if (session != null)
				session.close();
		}
	}

	public static Object get(Class clazz, Serializable id) {
		Session session = null;
		try {
			session = HibernateUtil.getSession();
			Object obj = session.get(clazz, id);
			return obj;
		} catch (HibernateException e) {
			throw e;
		} finally {
			if (session != null)
				session.close();
		}
	}

	public static Object get(String name, String scheduleName) {
		Session session = null;
		try {
			session = HibernateUtil.getSession();
			Query query = session.createQuery("from " + scheduleName + " as student where name=:name");
			query.setParameter("name", name);
			Object obj = query.uniqueResult();
			return obj;
		} catch (HibernateException e) {
			throw e;
		} finally {
			if (session != null)
				session.close();
		}

	}

	public static List getAll(String scheduleName) {
		Session session = null;
		try {
			session = HibernateUtil.getSession();
			Query query = session.createQuery("from " + scheduleName + " as student");
			List list = query.list();

			return list;
		} catch (HibernateException e) {
			throw e;
		} finally {
			if (session != null)
				session.close();
		}

	}


}
